<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>身份证号生成</title>
  <link rel="icon" href="./images/bitbug_favicon.ico" type="image/x-icon">
  <link rel="shortcut icon" href="./images/bitbug_favicon.ico" type="image/x-icon">
  <style>
    #example{
      margin: 20px auto;
      /*width: 600px;*/
      display: flex;
      justify-content: space-around;
    }
    .title{
      text-align: center;
    }
    .box{
      background-color: #ffffff;
      border: 1px solid #d7403f;
      padding: 1rem;
      position: relative;
    }
    .message{
      position: absolute;
      top: 0;
      left: 0;
      width: 520px;
      height: 168px;
      line-height: 168px;
      text-align: center;
      font-size: 30px;
      background-color: aqua;
      opacity: .7;
      z-index: -1;
    }
    .show-message{
      z-index: 2;
    }
    .selected{
      color: #d7403f;
      font-weight: 900;
    }
    select{
      text-align-last: center;
    }
    .submit-div{
      text-align: center;
      margin-top: 20px;
    }
    .sub-btn{
      display: inline-block;
      width: 116px;
      height: 30px;
      font-size: 18px;
      text-align: center;
      line-height: 30px;
      cursor: pointer;
      color: #ffffff;
      background-color: #d7403f;
      border-radius: 10px;
    }
    .result-item{
      height: 30px;
      line-height: 30px;
      border-bottom: 1px solid #d7403f;
    }
    .copy{
      width: 35px;
      height: 25px;
      display: inline-block;
      line-height: 25px;
      text-align: center;
      background-color: #cccccc;
      margin-left: 20px;
      cursor: pointer;
      opacity: 0.5;
    }
    .copy-success{
      margin-left: 20px;
      color: aqua;
    }
  </style>
</head>
<body>
  <div id="example">
    <div class="createIdCard">
      <h1 class="title">身份证号码在线生成</h1>
      <div class="box">
        <div class="address">
          请选择省市区：
          <select name="province" id="province" v-model="form.inputProvince" @change="provinceChange">
            <option value="" disabled>--请选择省--</option>
            <template v-for="item in provinceOptions">
              <option :value="item.value">{{item.name}}</option>
            </template>
          </select>
          <select name="city" id="city" v-model="form.inputCity" @change="cityChange">
            <option value="" disabled>--请选择市--</option>
            <template v-for="item in cityOptions">
              <option :value="item.value">{{item.name}}</option>
            </template>
          </select>
          <select name="town" id="town" v-model="form.inputCountry" @change="countryChange">
            <option value="" disabled>--请选择县--</option>
            <template v-for="item in countryOptions">
              <option :value="item.value">{{item.name}}</option>
            </template>
          </select>
        </div>
        <div class="date">
          请选择年月日：
          <select id="year" v-model="form.inputYear" @change="yearChange">
            <option value="" disabled>--请选择年--</option>
            <template v-for="item in yearOptions">
              <option :value="item.value">{{item.name}}</option>
            </template>
          </select>年
          <select name="month" id="month" v-model="form.inputMonth" @change="monthChange">
            <option value="" disabled>--请选择月份--</option>
            <template v-for="item in monthOptions">
              <option :value="item.value">{{item.name}}</option>
            </template>
          </select>月
          <select name="day" id="day" v-model="form.inputDay">
            <option value="" disabled>--请选择日期--</option>
            <template v-for="item in daysOptions">
              <option :value="item.value">{{item.name}}</option>
            </template>
          </select>日
        </div>
        <div class="gender">
          性别：
          <input class="male" type="radio" value="male" name="sex" v-model="form.sex">男
          <input class="female" type="radio" value="female" name="sex" v-model="form.sex">女
        </div>
        <div class="num">
          生成：
          <input class="number" v-model="form.createNum" type="text">个
        </div>
        <div class="submit-div">
          <span class="sub-btn" @click="toCreateIdCard">提交</span>
        </div>
        <div class="message" :class="message?'show-message':''">
          {{message}}
        </div>
      </div>
      <div class="result">
        <template v-for="(item,index) in result">
          <p class="result-item">
            <span :class="item.isSelected?'selected':''">{{item.idcard}}</span>
            <span class="copy" @click="copyIdCard(index)">复制</span>
            <span v-show="isIdCardSuccess===index" class="copy-success">复制成功</span>
          </p>
        </template>
      </div>
    </div>
    <div class="createPhone">
      <h1 class="title">手机号码在线生成</h1>
      <div class="createTel">
        <div class="num">
          生成：
          <input class="number" v-model="createTelNumbers" type="text">个
        </div>
        <div class="submit-div">
          <span class="sub-btn" @click="toCreateTel">提交</span>
        </div>
        <div class="result">
          <template v-for="(item,index) in telResult">
            <p class="result-item">
              <span :class="item.isSelected?'selected':''">{{item.telphone}}</span>
              <span class="copy" @click="copyTelphone(index)">复制</span>
              <span v-show="isTelSuccess===index" class="copy-success">复制成功</span>
            </p>
          </template>
        </div>
      </div>
    </div>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script>
    const baseUrl = 'http://rap2api.taobao.org/app/mock/234608';
    const provinceAPI = '/api/map/province';
    const cityAPI = '/api/map/city';
    const countryAPI = '/api/map/country';
    const proMessage = '请选择省份'
    const cityMessage = '请选择市'
    const countryMessage = '请选择区县'
    const yearMessage = '请选择年'
    const monthMessage = '请选择月份'
    const dayMessage = '请选择日期'
    const numMessage = '数字必须为大于等于0的整数'
    var vm = new Vue({
      el: "#example"
      ,data:{
        province:{},
        city:{},
        country:{},
        form:{
          inputProvince:'',
          inputCity:'',
          inputCountry: '',
          inputYear: '',
          inputMonth: '',
          inputDay: '',
          sex: 'male',
          createNum: 10
        },
        createTelNumbers: 10,
        message: '',
        isIdCardSuccess: null,
        isTelSuccess: null,
        provinceOptions: [],
        cityOptions: [],
        countryOptions: [],
        yearOptions: [],
        monthOptions: [],
        daysOptions: [],
        result:[],
        telResult: []
      }
      ,created(){
        this.initYearOptions();
        this.initProvince();
      }
      ,methods: {
        sendByGet(options){
          options = options || {};
          // 1.创建ajax对象
          let ajax = new XMLHttpRequest();
          // 2.创建http请求，并设置请求地址
          ajax.open('get',options.url);
          // 3.发送请求，get--null,post--params
          ajax.send(null);
          // 4.获取响应状态
          ajax.onreadystatechange = function () {
            // let res = JSON.parse();
            options.success([ajax.responseText])
          }
        }
        ,copyIdCard(index){
          this.copyText(this.result[index].idcard,index,this.result, 'idcard')
        }
        ,copyTelphone(index) {
          this.copyText(this.telResult[index].telphone, index, this.telResult, 'telphone')
        }
        ,copyText(str, index, arr, object){
          const el = document.createElement('textarea');
          el.value = str;
          document.body.appendChild(el);
          el.select();
          document.execCommand('copy');
          document.body.removeChild(el);
          if(object === 'idcard') {
            this.isIdCardSuccess = index;
          }
          if(object === 'telphone') {
            this.isTelSuccess = index
          }
          arr[index].isSelected = true;
          setTimeout(()=>{
            this.isIdCardSuccess = null;
            this.isTelSuccess = null;
          },1000)
        }
        ,initYearOptions(){
          let nowYear = new Date().getFullYear();
          let yearOptions = [];
          for (let i = nowYear; i >=1984 ; i--) {
            yearOptions.push({
              value: i,
              name: i
            })
          }
          this.yearOptions = yearOptions;
        }
        ,initMonthOptions(){
          let nowYear = new Date().getFullYear();
          let nowMonth = new Date().getMonth() + 1;
          let monthOptions = [];
          let months = this.form.inputYear === nowYear?nowMonth: 12;

          for (let i = months; i >=1 ; i--) {
            monthOptions.push({
              value: i,
              name: i
            })
          }
          this.monthOptions = monthOptions;
        }
        ,initDaysOptions(){
          let daysMap = new Map([
            [1,31],
            [2,this.form.inputYear %4===0&&this.form.inputYear %100 !==0?29:28],
            [3,31],
            [4,30],
            [5,31],
            [6,30],
            [7,31],
            [8,31],
            [9,30],
            [10,31],
            [11,30],
            [12,31],
          ])
          let nowYear = new Date().getFullYear();
          let nowMonth = new Date().getMonth()+1;
          let nowDay = new Date().getDay();
          let dayOptions = [];
          let days = this.form.inputMonth === nowMonth&&this.form.inputYear === nowYear? nowDay: daysMap.get(this.form.inputMonth);
          for (let i = days; i >=1 ; i--) {
            dayOptions.push({
              value: i,
              name: i
            })
          }
          this.daysOptions = dayOptions;
        }
        ,initProvince(){
          let provinceOptions = [];
          axios.get('./province.json')
            .then((res)=>{
              console.log('res',res);
              let province = res.data;
              this.province = province;
              for (let i = 0; i < province.length; i++) {
                let item = province[i];
                provinceOptions.push({value: item.id,name: item.name})
              }
              this.provinceOptions = provinceOptions;
            })
            .then(()=>{
              axios.get('./city.json')
                .then((res)=>{
                  console.log('res',res);
                  let city = res.data;
                  this.city = city;
                })
            })
            .then(()=>{
              axios.get('./country.json')
                .then((res)=>{
                  console.log('res',res);
                  let country = res.data;
                  this.country = country;
                })
            })
        }
        ,initCity(){
          let cityOptions = [];
          let city = this.city[this.form.inputProvince];
          for (let i = 0; i < city.length; i++) {
            let item = city[i];
            cityOptions.push({value: item.id,name: item.name})
          }
          this.cityOptions = cityOptions;
        }
        ,initCountry(){
          let countryOptions = [];
          let country = this.country[this.form.inputCity];
          for (let i = 0; i < country.length; i++) {
            let item = country[i];
            countryOptions.push({value: item.id,name: item.name})
          }
          this.countryOptions = countryOptions;
        }
        ,yearChange(){
          this.initMonthOptions();
        }
        ,monthChange(){
          this.initDaysOptions();
        }
        ,provinceChange(){
          this.initCity()
        }
        ,cityChange(){
          this.initCountry();
        }
        ,countryChange(){

        }
        ,toCreateIdCard(){
          if(!this.form.inputProvince){
            this.message = proMessage
            setTimeout(()=>{
              this.message = ''
            },800)
            return;
          }
          if(!this.form.inputCity){
            this.message = cityMessage
            setTimeout(()=>{
              this.message = ''
            },800)
            return;
          }
          if(!this.form.inputCountry){
            this.message = countryMessage
            setTimeout(()=>{
              this.message = ''
            },800)
            return;
          }
          if(!this.form.inputYear){
            this.message = yearMessage
            setTimeout(()=>{
              this.message = ''
            },800)
            return;
          }
          if(!this.form.inputMonth){
            this.message = monthMessage
            setTimeout(()=>{
              this.message = ''
            },800)
            return;
          }
          if(!this.form.inputDay){
            this.message = dayMessage
            setTimeout(()=>{
              this.message = ''
            },800)
            return;
          }
          if(!this.form.createNum || this.form.createNum<= 0 || Math.ceil(this.form.createNum)>this.form.createNum || typeof this.form.createNum !== 'number'){
            this.message = numMessage
            setTimeout(()=>{
              this.message = ''
            },800)
            return;
          }

          let idcards = [];
          for (let i = 0; i < this.form.createNum; i++) {
            idcards.push({idcard:this.createIdCard(),isSelected: false})
          }

          this.result = idcards;
        }
        ,toCreateTel() {
          const telNums = this.createTelNumbers;
          // if(!telNums || telNums<= 0 || Math.ceil(telNums)>telNums || typeof telNums !== 'number'){
          //   this.message = numMessage
          //   setTimeout(()=>{
          //     this.message = ''
          //   },800)
          //   return;
          // }
          let telphones = []
          for (let i = 0; i < telNums; i++) {
            telphones.push({telphone: this.createTel(),isSelected: false})
          }
          this.telResult = telphones
        }
        ,createTel() {
          const headerNums = new Array("139","138","137","136","135","134","159","158","157","150","151","152","188","187","182","183","184","178","130","131","132","156","155","186","185","176","133","153","189","180","181","177");
          const headerNum = headerNums[parseInt(Math.random() * 10 ,10)]
          const bodyNum = Math.random().toString().replace('0.', '').slice(0, 8)
          return headerNum + bodyNum
        }
        ,createIdCard(){
          let idcard = '';
          let { inputCountry, inputYear, inputMonth, inputDay, sex } = this.form;
          let randNum = this.randThree(sex)
          idcard += inputCountry.slice(0,6) + inputYear+ this.add0(inputMonth)+ this.add0(inputDay)+randNum;
          idcard = this.jisuanLast(idcard);
          return idcard
        }
        ,randThree(sex){
          let random1 = Math.random() * 1000
          let res = parseInt(random1>=100?random1:Math.random() * 1000);
          if(sex === 'male'){
            while (res%2 === 0){
              let random2 = Math.random() * 1000
              res = parseInt(random2>=100?random2:Math.random() * 1000);
            }
            return res;
          }else{
            while (res%2 !== 0){
              let random3 = Math.random() * 1000
              res = parseInt(random3>100?random3:Math.random() * 1000);
            }
            return res;
          }
        }
        ,add0(val){
          return val<10? '0'+val:val;
        }
        ,jisuanLast(idcard){
          let one = Number(idcard.slice(0,1));
          let two = Number(idcard.slice(1,2));
          let three = Number(idcard.slice(2,3));
          let four = Number(idcard.slice(3,4));
          let five = Number(idcard.slice(4,5));
          let six = Number(idcard.slice(5,6));
          let seven = Number(idcard.slice(6,7));
          let eight = Number(idcard.slice(7,8));
          let nine = Number(idcard.slice(8,9));
          let ten = Number(idcard.slice(9,10));
          let eleven = Number(idcard.slice(10,11));
          let twlven = Number(idcard.slice(11,12));
          let thirteen = Number(idcard.slice(12,13));
          let fourteen = Number(idcard.slice(13,14));
          let fifteen = Number(idcard.slice(14,15));
          let sixteen = Number(idcard.slice(15,16));
          let seventeen = Number(idcard.slice(16,17));
          let num = one*7+two*9+three*10+four*5+five*8+six*4+seven*2+eight*1+nine*6+ten*3+eleven*7+twlven*9+thirteen*10+fourteen*5+fifteen*8+sixteen*4+seventeen*2;
          let yushuMap = new Map([
              [0,'1'],
              [1,"0"],
              [2,'X'],
              [3,'9'],
              [4,'8'],
              [5,'7'],
              [6,'6'],
              [7,'5'],
              [8,'4'],
              [9,'3'],
              [10,'2']
          ])
          idcard += String(yushuMap.get(num%11))
          return idcard;
        }
      }
    })
  </script>
</body>
</html>
